package com.example.kkblog.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.kkblog.controller.dto.ResponseDto;
import com.example.kkblog.domain.Dynamic;
import com.example.kkblog.domain.Topic;
import com.example.kkblog.domain.dto.ArticlePreDto;
import com.example.kkblog.domain.dto.DynamicPreDto;
import com.example.kkblog.domain.dto.TopicDto;
import com.example.kkblog.domain.dto.UserDto;
import com.example.kkblog.domain.query.ArticleQuery;
import com.example.kkblog.domain.query.DynamicQuery;
import com.example.kkblog.mapper.*;
import com.example.kkblog.service.KKBlogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author xiaoke
 * @date 2024/4/7
 */
@Controller
@RequestMapping({ "/index"})
public class indexController {
    @Autowired
    private DynamicMapper dynamicMapper;

    @Autowired
    private TopicMapper topicMapper;

    @Autowired
    private LikeMapper likeMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private KKBlogService kkBlogService;

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private FollowMapper followMapper;

    public void getDailyCheckInfo(Model model, UserDto loginUser) {
        // 查询用户排行榜
        model.addAttribute("ranks", userMapper.selectScoresRank());
        if (loginUser == null) {
            model.addAttribute("dailyCheck", null);
        } else {
            model.addAttribute("dailyCheck", kkBlogService.userCheckToday(loginUser.getId()));
        }
        model.addAttribute("checkUsers", kkBlogService.selectCheckUserTop());
    }

    @RequestMapping({"/", ""})
    public String index(Model model, HttpSession session) {
        // 查询主题
        List<TopicDto> topicDtos = topicMapper.selectAvailableTopics();
        if (!topicDtos.isEmpty()) {
            topicDtos.get(0).setSelected(true);
        }
        model.addAttribute("topics", topicDtos);
        List<DynamicPreDto> dynamicPreDtos = dynamicMapper.selectNewestDynamics();
        UserDto loginUser = (UserDto) session.getAttribute("user");
        if (loginUser != null) {
            dynamicPreDtos.forEach(item -> {
                item.setLiked(likeMapper.selectIfUserLike(loginUser.getId() + "_" + item.getId()) > 0);
            });
        }
        model.addAttribute("dynamics", dynamicPreDtos);
        getDailyCheckInfo(model, loginUser);
        return "index";
    }

//    @SuppressWarnings("all")
    @RequestMapping("/topics/{id}")
    public String topics(@PathVariable int id, Model model, HttpSession session) {
        // 查询主题
        List<TopicDto> topicDtos = topicMapper.selectAvailableTopics();
        TopicDto selectedTopic = null;
        for (TopicDto topicDto : topicDtos) {
            if (topicDto.getId() == id) {
                topicDto.setSelected(true);
                selectedTopic = topicDto;
                break;
            }
        }
        UserDto loginUser = (UserDto) session.getAttribute("user");
        model.addAttribute("topics", topicDtos);
        List<DynamicPreDto> dynamicPreDtos;
        assert selectedTopic != null;
        if ("最新".equals(selectedTopic.getName())) {
            dynamicPreDtos = dynamicMapper.selectNewestDynamics();
        } else if ("推荐".equals(selectedTopic.getName())){
            dynamicPreDtos = dynamicMapper.selectRecommendDynamics();
        } else if ("关注".equals(selectedTopic.getName())){
            if (loginUser != null) {
                dynamicPreDtos = dynamicMapper.selectFollowDynamics(loginUser.getId());
            } else {
                dynamicPreDtos = new ArrayList<>();
            }
        } else {
            dynamicPreDtos = dynamicMapper.selectDynamicsByTopicId(id);
        }
        if (loginUser != null) {
            dynamicPreDtos.forEach(item -> {
                item.setLiked(likeMapper.selectIfUserLike(loginUser.getId() + "_" + item.getId()) > 0);
            });
        }
        model.addAttribute("dynamics", dynamicPreDtos);
        getDailyCheckInfo(model, loginUser);
        return "index";
    }


    // 加载更多
    @ResponseBody
    @GetMapping("/more")
    public ResponseDto loadMore(@RequestParam("dynamicId") Integer dynamicId,
                                @RequestParam("topicId") Integer topicId,
                                @RequestParam(value = "pageNum", required = false) Integer pageNum,
                                HttpSession session) {
        UserDto loginUser = (UserDto) session.getAttribute("user");
        Topic topic = topicMapper.selectById(topicId);
        List<DynamicPreDto> dynamicPreDtos;
        switch (topic.getName()) {
            case "最新":
                dynamicPreDtos = dynamicMapper.selectMoreNewestDynamics(dynamicId);
                break;
            case "推荐":
                dynamicPreDtos = dynamicMapper.selectMoreRecommendDynamics(pageNum * 8);
                break;
            case "关注":
                if (loginUser == null) {
                    dynamicPreDtos = new ArrayList<>();
                } else {
                    dynamicPreDtos = kkBlogService.selectMoreFollowDynamics(loginUser.getId(), dynamicId);
                }
                break;
            default:
                Dynamic query = new Dynamic();
                query.setId(dynamicId);
                query.setTopicId(topicId);
                dynamicPreDtos = dynamicMapper.selectMoreDynamicsByTopicId(query);
                break;
        }
        if (loginUser != null) {
            dynamicPreDtos.forEach(item -> {
                item.setLiked(likeMapper.selectIfUserLike(loginUser.getId() + "_" + item.getId()) > 0);
            });
        }
        return ResponseDto.Success("查询成功！", dynamicPreDtos);
    }

    @GetMapping("/article")
    public String article(Model model, HttpSession session) {
        List<ArticlePreDto> articlePreDtos = articleMapper.selectNewestArticles();
        model.addAttribute("articles", articlePreDtos);
        getDailyCheckInfo(model, (UserDto) session.getAttribute("user"));
        return "article";
    }

    // 加载更多
    @ResponseBody
    @GetMapping("/article/loadMore")
    public ResponseDto loadMoreArticle(@RequestParam("articleId") Integer articleId,
                                @RequestParam(value = "pageNum", required = false) Integer pageNum,
                                HttpSession session) {
        return ResponseDto.Success("查询成功！", articleMapper.selectMoreNewestArticles(articleId));
    }

    // 搜索
    @GetMapping("/search")
    public String search(@RequestParam("key") String key,
                         @RequestParam(value = "type", required = false) String type,
                         Model model,
                         HttpSession session) {
        UserDto loginUser = (UserDto) session.getAttribute("user");
        getDailyCheckInfo(model, loginUser);
        model.addAttribute("searchKey", key);
        // 搜索用户
        if (type == null || "user".equals(type)) {
            List<UserDto> searchUsers = kkBlogService.selectUserByKey(key.trim(), 0);
            if (loginUser != null) {
                // 查询自己的关注列表
                List<Integer> followingIds = followMapper.selectFollowedIds(loginUser.getId());
                searchUsers.forEach(item -> item.setFollow(followingIds.contains(item.getId())));
            }
            model.addAttribute("searchUsers", searchUsers);
            model.addAttribute("searchPage", "user");
            return "search/user-search";
        } else if ("article".equals(type)) {
            model.addAttribute("searchArticles", articleMapper.selectArticlesByKey(new ArticleQuery(0, 5, key)));
            return "search/article-search";
        } else {
            List<DynamicPreDto> dynamicPreDtos = dynamicMapper.selectByKey(new DynamicQuery(0, 8, key));
            if (loginUser != null) {
                dynamicPreDtos.forEach(item -> {
                    item.setLiked(likeMapper.selectIfUserLike(loginUser.getId() + "_" + item.getId()) > 0);
                });
            }
            model.addAttribute("searchTopics", dynamicPreDtos);
            return "search/topic-search";
        }
    }

    @ResponseBody
    @GetMapping("/search/more")
    public ResponseDto searchMore(@RequestParam("type") String type,
                                  @RequestParam("lastId") Integer lastId,
                                  @RequestParam("key") String key,
                                  HttpSession session) {
        UserDto loginUser = (UserDto) session.getAttribute("user");
        // 搜索用户
        if (type == null || "user".equals(type)) {
            List<UserDto> searchUsers = kkBlogService.selectUserByKey(key.trim(), lastId);
            if (loginUser != null) {
                // 查询自己的关注列表
                List<Integer> followingIds = followMapper.selectFollowedIds(loginUser.getId());
                searchUsers.forEach(item -> item.setFollow(followingIds.contains(item.getId())));
            }
            return ResponseDto.Success("操作成功！", searchUsers);
        } else if ("article".equals(type)) {
            return ResponseDto.Success("操作成功！", articleMapper.selectArticlesByKey(new ArticleQuery(lastId, 5, key)));
        } else {
            List<DynamicPreDto> dynamicPreDtos = dynamicMapper.selectByKey(new DynamicQuery(lastId, 8, key));
            if (loginUser != null) {
                dynamicPreDtos.forEach(item -> {
                    item.setLiked(likeMapper.selectIfUserLike(loginUser.getId() + "_" + item.getId()) > 0);
                });
            }
            return ResponseDto.Success("操作成功！", dynamicPreDtos);
        }
    }
}
